/*
 Source: ufxTrader.java
 Software Copyright: Hundsun Technologies Inc.
 System: UFX Future Demo (Asynchronous)
 Module: Main Function
 Describition:
 This class is the main class for future demo, the documents for function description and Java programming helper can be found at ufx 
 website: https://ufx.hscloud.cn/ufx/html/doc/index.html
 Function id include: 819706 ,819707,819709,819710,819711,620001-33101
 author: Kai Zhan
 Date:2016/05/12
 Others:
 This demo is a sample for using Hundsun UFX System, we are highly not recommand any user to use this demo at any real market，for more details 
 please read <T2SDK JAVA Developer Manual>
 */
package com.hmkj.core.api.ufx.call;

import com.alibaba.fastjson.JSON;
import com.hmkj.boot.utils.SpringContextUtils;
import com.hmkj.core.api.ufx.mc.UFXMC;
import com.hmkj.core.api.ufx.model.req.EntrustNativeReq;
import com.hmkj.core.api.ufx.model.req.EntrustOtcReq;
import com.hmkj.core.api.ufx.model.res.EntrustRes;
import com.hmkj.core.api.ufx.model.res.LoginRes;
import com.hmkj.core.api.ufx.trade.UfxTradeSync;
import com.hmkj.core.constant.ConfigNID;
import com.hmkj.core.exception.UFXLoginException;
import com.hmkj.core.po.commo.Commo;
import com.hmkj.core.service.cache.RedisService;
import com.hundsun.mcapi.MCServers;
import com.hundsun.t2sdk.impl.client.T2Services;
import com.hundsun.t2sdk.interfaces.T2SDKException;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

/**
 * 期货交易相关请求实例
 */
@Slf4j
public class TransactionCall {

    private static T2Services server = T2Services.getInstance();//T2实例化

    private static UFXMC ufxmc = new UFXMC();

    private static UfxTradeSync ufxTradeSync = new UfxTradeSync();

    private static TransactionCall transactionCall = new TransactionCall();


    private static String SENDER; // 客户编号

    private static int ORG_OTC;// 外盘期货机构编号

    private static int ORG_NATIVE;// 内盘期货机构编号

    private TransactionCall() {

    }


    public static TransactionCall getInstance() {
        RedisService redisService = SpringContextUtils.getBean("redisService");
        SENDER = redisService.get(ConfigNID.API_SENDER);
        ORG_OTC = redisService.get(ConfigNID.API_ORG_OTC, Integer.class);
        ORG_NATIVE = redisService.get(ConfigNID.API_ORG_NATIVE, Integer.class);
        return transactionCall;
    }


    /**
     * 获取T2SDK配置文件中配置的连接
     * 启动T2SDK，只需要在服务器启动时调用一次就可以了
     */
    public void initT2() throws Exception {
        server.setT2sdkConfigString("classpath:config/t2sdk_hundsun_trade-config.xml");//配置文件路径
        server.init();
        server.start();
        MCServers.MCInit();

//        // 测试内盘登录
//        LoginRes res = accountLogin("1","097725","ab1234",2);
//        log.info("登录结果"+ JSON.toJSONString(res));
//        LoginRes res1 = accountLogin("1","114504","lwd123456",2);
//        log.info("登录结果"+ JSON.toJSONString(res1));

//        qryAccountNative("2b3ac1bd7ced47986a3a8c94de91188e","0");


    }

    /**
     * 订阅交易主推信息 （委托回报、成交回报）
     */
    public void reqTradePush() {
        // 订阅国际期货交易主推
        ufxmc.reqFunctionTradeOut();
        // 订阅国内期货交易主推
        ufxmc.reqFunctionTradeIn();
    }


    /**
     * 外盘客户登录
     *
     * @param opStation   站点地址
     * @param fundAccount 资金账号
     * @param password    密码
     * @param type        账号类型：2内盘  1外盘
     * @return LoginRes
     */
    public LoginRes accountLogin(String opStation, String fundAccount, String password, int type) throws Exception {
        ufxTradeSync.Init();

        String result;
        if (Commo.TYPE.T1.code == type) {
            // 外盘账号登录
            result = ufxTradeSync.ReqFunction819450(opStation, fundAccount, password, SENDER, ORG_OTC);
        } else {
            // 内盘账号登录
            result = ufxTradeSync.ReqFunction819700(opStation, fundAccount, password, SENDER, ORG_NATIVE);
            Map<String, String> data = analysisData(result);
            settlementConfirmNative(data.get("user_token"));
        }

        log.info(result);
        //返回信息如下：
        /*
            client_name,fund_account,user_token,
            ,Q1162942521,54457333185f84bb8583f0bc2a730c78,
         */
        Map<String, String> data = analysisData(result);

        LoginRes res = new LoginRes(t -> {
            t.setFundAccount(data.get("fund_account"));
            t.setUserToken(data.get("user_token"));
        });

        return res;
    }


    /**
     * 外盘普通委托
     *
     * @param req 请求参数
     * @return EntrustRes
     */

    public EntrustRes tradeEntrustOtc(EntrustOtcReq req) throws T2SDKException, UFXLoginException {
        ufxTradeSync.Init();

        String result = ufxTradeSync.ReqFunction819455(req, SENDER, ORG_OTC);
        log.info(result);
        //返回信息如下：
        /*
            entrust_reference,futu_entrust_no,
            Q1162942521,54457333185f84bb8583f0bc2a730c78,
         */
        Map<String, String> data = analysisData(result);

        EntrustRes res = new EntrustRes(t -> {
            t.setFutuEntrustNo(data.get("futu_entrust_no"));
            t.setEntrustReference(data.get("entrust_reference"));
        });
        return res;
    }

    /**
     * 内盘普通委托
     *
     * @param req 请求参数
     * @return EntrustRes
     */

    public EntrustRes tradeEntrustNative(EntrustNativeReq req) throws T2SDKException, UFXLoginException {
        ufxTradeSync.Init();

        String result = ufxTradeSync.ReqFunction819706(req, SENDER, ORG_NATIVE);
        log.info(result);
        //返回信息如下：
        /*
            entrust_reference,entrust_no,
            Q1162942521,54457333185f84bb8583f0bc2a730c78,
         */
        Map<String, String> data = analysisData(result);

        EntrustRes res = new EntrustRes(t -> {
            t.setFutuEntrustNo(data.get("entrust_no"));
            t.setEntrustReference(data.get("entrust_reference"));
        });
        return res;
    }


    /**
     * 内盘客户资金查询
     *
     * @param userToken 用户令牌
     * @param moneyType 币种
     * @return void
     */

    public void qryAccountNative(String userToken, String moneyType) throws T2SDKException, UFXLoginException {
        ufxTradeSync.Init();

        String result = ufxTradeSync.ReqFunction819708(userToken, moneyType, SENDER, ORG_NATIVE);
        log.info(result);

        Map<String, String> data = analysisData(result);
        log.info(JSON.toJSONString(data));

    }


    /**
     * 内盘客户账单确认
     *
     * @param userToken 用户令牌
     * @return void
     */

    public void settlementConfirmNative(String userToken) throws T2SDKException, UFXLoginException {
        ufxTradeSync.Init();

        String result = ufxTradeSync.ReqFunction819705(userToken, SENDER, ORG_NATIVE);
        log.info(result);
    }

    /**
     * 整理返回数据
     *
     * @param result
     * @return
     */
    private Map<String, String> analysisData(String result) {
        // 接收数据数组
        String[] keys = result.split("\n")[0].split(",");
        String[] vals = result.split("\n")[1].split(",");

        Map<String, String> datas = new HashMap<>();
        for (int i = 0; i < keys.length; i++) {
            datas.put(keys[i], vals[i]);
        }
        return datas;
    }

//    /**
//     * 委托撤单
//     *
//     * @param req 请求参数
//     * @return EntrustRes
//     */
//    public EntrustRes tradeEntrustWithdraw(EntrustWithdrawReq req) throws Exception {
//        ufxTradeSync.Init();
//
//        String result = ufxTradeSync.ReqFunction819456(req);
//        log.info(result);
//        //返回信息如下：
//        /*
//            entrust_reference,futu_entrust_no,
//            Q1162942521,54457333185f84bb8583f0bc2a730c78,
//         */
//        String[] data = result.split("\n");
//        EntrustRes res = new EntrustRes();
//        for (int i = data.length - 1; i > 0; i--) {
//            String[] args = data[i].split(",");
//            res.setEntrustReference(args[0]);
//            res.setFutuEntrustNo(args[1]);
//        }
//        return res;
//    }
//
//
//    /**
//     * 委托查询
//     *
//     * @param fundAccount   请求参数
//     * @param userToken     请求参数
//     * @param futuEntrustNo 请求参数
//     * @return QueryEntrustRes
//     */
//    public QueryEntrustRes queryEntrust(String fundAccount, String userToken, String futuEntrustNo) throws Exception {
//        ufxTradeSync.Init();
//
//        String result = ufxTradeSync.ReqFunction819460(fundAccount, userToken, futuEntrustNo);
//        log.info(result);
//        //返回信息如下：
//        /*
//            entrust_reference,futu_entrust_no,
//            Q1162942521,54457333185f84bb8583f0bc2a730c78,
//         */
//        String[] data = result.split("\n");
//        QueryEntrustRes res = new QueryEntrustRes();
//        for (int i = data.length - 1; i > 0; i--) {
//            String[] args = data[i].split(",");
//            res.setInitDate(Integer.parseInt(args[0]));
//            res.setFutuEntrustNo(args[1]);
//            res.setFutuEntrustStatus(args[2]);
//            res.setEntrustTime(Integer.parseInt(args[3]));
//            res.setFundAccount(args[4]);
//            res.setFutuExchType(args[5]);
//            res.setCommodityType(args[6]);
//            res.setContractCode(args[7]);
//            res.setSecondCode(args[8]);
//            res.setFutuProductType(args[9]);
//            res.setEntrustBs(args[10]);
//            res.setFutuEntrustPrice(new BigDecimal(args[11]));
//            res.setEntrustAmount(Integer.parseInt(args[12]));
//            res.setBusinessAmount(Integer.parseInt(args[13]));
//            res.setTimeCondition(args[14]);
//            res.setValidDate(args[15]);
//            res.setFutuEntrustProp(args[16]);
//            res.setEntrustReference(args[17]);
//        }
//        return res;
//    }


}
